package com.feonix.blockchain.controller;

import com.alibaba.fastjson.JSON;
import com.feonix.blockchain.dao.BlockChain;
import com.feonix.blockchain.pojo.Block;
import com.feonix.blockchain.pojo.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wallet")
public class WalletController {
    @Autowired
    private ServletContext servletContext;

    // 发起新交易
    @RequestMapping("/trans")
    public String trans(Transaction trans) {
        Map<String, Object> resp = new HashMap<String, Object>();

        // 判断获取到的交易参数是否完整
        if (trans == null || trans.getSender() == null || trans.getRecipient() == null || trans.getAmount() <= 0) {
            resp.put("message", "Error: Missing values");
            return JSON.toJSONString(resp);
        }

        // 发送交易
        BlockChain blockChain = BlockChain.getInstance();
        int index = blockChain.newTransactions(trans.getSender(), trans.getRecipient(), trans.getAmount());

        // 向客户端返回处理结果
        resp.put("message", "Transaction will be added to Block " + index);

        return JSON.toJSONString(resp);
    }

    // 挖矿
    @RequestMapping("/mine")
    public String mine() {
        BlockChain blockChain = BlockChain.getInstance();
        Block lastBlock = blockChain.getLastBlock();
        long lastProof = Long.parseLong(lastBlock.getProof() + "");
        long proof = blockChain.proofOfWork(lastProof);

        // 给工作量证明的节点提供奖励，发送者为 "0" 表明是新挖出的币
        String uuid = (String) servletContext.getAttribute("uuid");
        blockChain.newTransactions("0", uuid, 1);

        // 构建新的区块
        Block newBlock = blockChain.newBlock(proof, null);
        Map<String, Object> resp = new HashMap<String, Object>();
        resp.put("message", "New Block Forged");
        resp.put("block", newBlock);

        return JSON.toJSONString(resp);
    }

    // 查看整个区块链数据
    @RequestMapping("/chain")
    public String fullChain() {
        BlockChain blockChain = BlockChain.getInstance();
        Map<String, Object> resp = new HashMap<String, Object>();
        resp.put("chain", blockChain.getChain());
        resp.put("length", blockChain.getChain().size());

        return JSON.toJSONString(resp);
    }
}
